<template>
  <div>
    <!-- 头部 -->
    <a-form ref="searchRef" :rules="rules" :model="searchForm" :hideRequiredMark="true" style="margin-bottom: 20px">
      <a-row>
        <a-col :span="4" :offset="1">
          <a-form-item name="saleValue" label="">
            <a-input placeholder="根据编号、标题模糊搜索" v-model:value="searchForm.titleOrnumber"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="4" :offset="1">
          <a-form-item name="saleValue" label="文章类型：">
            <a-select ref="select" placeholder="请选择" allowClear v-model:value="searchForm.type" @change="handleChange" @focus="focus">
              <a-select-option v-for="item in artStatusOptions" :value="item.id" :key="item.id">{{ item.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="2" :offset="1">
          <a-button type="primary" @click="search" class="d-a-center">搜索</a-button>
        </a-col>
        <a-col :span="2">
          <a-button @click="reset" class="d-a-center">重置</a-button>
        </a-col>
      </a-row>
    </a-form>

    <!-- 列表 -->
    <a-table
      :columns="columns"
      :data-source="list"
      bordered
      rowKey="key"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <!-- :row-selection="rowSelection" -->
      <template #title><a-button type="primary" @click="add" v-has="{ a: $route, b: 2 }" class="d-a-center">新增</a-button></template>
      <template #type="{ record }">
        <div>{{ artType[record.type] }}</div>
      </template>
      <template #classify="{ record }">
        <div v-if="record.serviceId">
          {{ record.serviceId }}
        </div>
      </template>
      <template #stack="{ record, index }">
        <div @click="changeStack(record.status, index, record.id)">
          <a-switch v-model:checked="record.status" :checkedValue="0" :unCheckedValue="1" />
        </div>
      </template>
      <template #operation="{ record }">
        <a-button type="link" @click="handleToTop(record.key)" v-has="{ a: $route, b: 2 }">置顶</a-button>
        <a-button type="link" @click="edit(record, '编辑')" v-has="{ a: $route, b: 2 }">编辑</a-button>
        <a-button type="link" @click="edit(record, '查看')" v-has="{ a: $route, b: 1 }">查看</a-button>
        <a-button type="link" danger @click="del(record.key)" v-has="{ a: $route, b: 2 }">删除</a-button>
      </template>
    </a-table>
    <!-- 多项删除 -->
    <!-- <a-button type="danger" @click="listDel">删除</a-button> -->

    <div>
      <!-- 知识库详情弹窗 -->
      <a-modal v-if="visible" :visible="visible" :title="modalTitle" @cancel="closeModal('visible')" width="50%" :maskClosable="false">
        <template v-slot:footer>
          <div class="d-j-around">
            <a-button @click="closeModal('visible')" class="d-a-center">关闭</a-button>
            <a-button v-if="modalTitle != '查看'" type="primary" @click="addArticle" class="d-a-center">确定</a-button>
          </div>
        </template>

        <a-form :model="form" :rules="rules" :labelCol="labelCol" ref="formRef">
          <a-form-item label="标题" name="title">
            <a-input placeholder="请输入标题" :disabled="modalTitle == '查看'" v-model:value="form.title" allow-clear></a-input>
          </a-form-item>
          <a-form-item label="发布人" name="issuerType">
            <a-select ref="select" v-model:value="form.issuerType" @focus="focus" @change="handleChange" placeholder="请选择">
              <a-select-option v-for="item in publish" :value="item.id" :disabled="modalTitle == '查看'" :key="item.id">{{
                item.name
              }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-col :span="12">
            <a-form-item label="列表图" name="titleImgPath">
              <a-upload
                v-model:file-list="titleImgPath"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="1"
                :customRequest="uploadDetail_image"
                :disabled="modalTitle == '查看'"
              >
                <div v-if="titleImgPath.length < 1" class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
              文件大小不能超过100kb
            </a-form-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-item label="内容图" name="contentImg">
              <a-upload
                v-model:file-list="contentImg"
                list-type="picture-card"
                class="avatar-uploader"
                :maxCount="7"
                :customRequest="uploadDetail_imgPath"
                :disabled="modalTitle == '查看'"
              >
                <div class="ant-upload-text">
                  <plus-outlined />
                </div>
              </a-upload>
              文件大小不能超过100kb
            </a-form-item>
          </a-col> -->
          <!-- <a-col :span="18">
            <a-form-item label="内容" name="content">
              <a-textarea
                :rows="4"
                placeholder="请输入内容"
                :disabled="modalTitle == '查看'"
                v-model:value="form.content"
              />
            </a-form-item>
          </a-col> -->
          <a-col :span="24">
            <a-form-item label="内容" style="width: 100%; height: 360px !important">
              <div id="wangeditor" style="width: 100%; height: 360px !important">
                <div ref="editorElem" style="width: 100%; height: 100px !important"></div>
              </div>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="是否置顶" name="top">
              <a-switch v-model:checked="form.top" :disabled="modalTitle == '查看'" :checkedValue="1" :unCheckedValue="0" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="文章类型" name="type">
              <a-radio-group v-model:value="form.type" :disabled="modalTitle == '查看'">
                <a-radio :value="1">行业发展</a-radio>
                <a-radio :value="2">护理知识</a-radio>
                <a-radio :value="3">专业课程</a-radio>
                <a-radio :value="4">平台活动</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-form>
      </a-modal>
    </div>
  </div>
</template>
<script>
import E from 'wangeditor'
import { url } from '@/utils/options'
import { reactive, ref, computed, createVNode, watch, toRefs, unref, toRaw, isReactive, toRef } from 'vue'
import { publish, swiperType, artType } from '@/utils/dict.js'
import { CheckOutlined, EditOutlined, ExclamationCircleOutlined, QuestionCircleOutlined } from '@ant-design/icons-vue'
import { uploadPicture } from '@/api/service/index.js'
import { Modal, message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import * as api from '@/api/content/know.js'
import { selectAllService, selectAllType } from '@/api/service/index.js'
import { deleteObjBlank } from '@/assets/js/common.js'
import { useModal } from '@/hooks'

export default {
  setup() {
    const editorElem = ref(null)
    const searchRef = ref('')
    const formRef = ref('')

    const data = reactive({
      editor: '',
      flag: false,
      list: [],
      loading: true,
      visible: false,
      serviceList: [], //分类列表
      detaiList: [],
      consumables: [], //默认绑定ID即可
      statusAct: 0,
      searchForm: {
        type: 1
      },
      typeList: [],
      form: { top: 0 },
      value: [], //分类-这个远程加载的数据好像不可以哎
      defaultValue: [],
      titleImgPath: [],
      contentImg: [],
      publish,
      swiperType: true ? [...swiperType.splice(0, 1)] : [...swiperType],
      artType,
      type: ''
    })

    const title = ref('') //分类名称

    const modalTitle = ref('新增')
    const rules = {
      issuerType: [{ required: true, message: '请选择' }],
      title: [{ required: true, message: '请输入' }],
      // titleImgPath: [{ required: true, message: "请上传" }],
      // contentImg: [{ required: true, message: "请上传" }],
      content: [{ required: true, message: '请输入' }],
      type: [{ required: true }]
      // top:[{ required: true, message: "请选择"}]
    }
    const rules1 = {
      name: [{ required: true, message: '请输入耗材名称!' }],
      sellPrice: [{ required: true, message: '请输入销售价!' }],
      serviceId: [{ required: true, message: '请输入服务类型!' }],
      typeId: [{ required: true, message: '请输入服务分类!' }],
      bazaarPrice: [{ required: true, message: '请输入市场价格!' }],
      bagNumber: [{ required: true, message: '请输入耗材编号!' }]
      // value: [{ required: true, message: "请选择耗材分类!" }],
    }

    // 分页器
    const page = reactive({
      current: 1,
      pageSize: 10,
      total: 0
    })
    const artStatusOptions = reactive([
      {
        name: '行业发展',
        id: 1
      },
      {
        name: '护理知识',
        id: 2
      },
      {
        name: '专业课程',
        id: 3
      },
      {
        name: '平台活动',
        id: 4
      }
    ])
    const delListId = ref([]) //删除数组ID集合
    const chooseStatus = (status, index) => {
      data.statusAct = index
      data.searchForm.status = status
      page.current = 1
      init()
    }
    // 查询
    const search = query => {
      page.current = 1
      init()
    }
    const reset = () => {
      data.searchForm = {}
      search()
    }
    const columns = [
      {
        title: '文章类型',
        dataIndex: 'type',
        className: 'table',
        slots: {
          customRender: 'type'
        }
      },
      {
        title: '编号',
        dataIndex: 'id',
        className: 'table'
      },
      {
        title: '标题',
        dataIndex: 'title',
        className: 'table'
      },
      {
        title: '发布人',
        dataIndex: 'issuerType',
        className: 'table'
      },
      {
        title: '排序',
        dataIndex: 'weight',
        className: 'table'
      },
      {
        title: '发布时间',
        dataIndex: 'createdTime',
        className: 'table'
      },

      {
        title: '操作',
        dataIndex: 'operation',
        className: 'table',
        slots: {
          customRender: 'operation'
        }
      }
    ]

    // 分页器
    const pagination = computed(() => ({
      current: page.current,
      pageSize: page.pageSize,
      pageSizeOptions: ['10', '20', '30'],
      showTotal: (total, range) => {
        return '共' + total + '条'
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true
    }))

    // 分页器改变的时候
    const handleTableChange = (pagination, filters, sorter) => {
      console.log(pagination, '当前分页')
      page.current = pagination.current
      page.pageSize = pagination.pageSize

      // 请求列表接口
      init()
    }
    const cancel = () => {
      data.visible = false
      title.value = ''
      data.form = { top: 0 }
      data.consumables = []
    }
    function initEditor() {
      let baseURL = ''
      if (process.env.VUE_APP_MODE == "'development'") {
        // 本地调试: 记得将vue.config.js中的Proxy注打开
        baseURL = '/api'
      } else {
        // 发布到正式服务器上：记得把vue.config.js中Proxy注释掉
        baseURL = url
        // baseURL = "http://192.168.0.32:5004/houtai";
      }
      data.editor = new E(editorElem.value) //获取组件并构造编辑器
      // data.editor.config.uploadImgShowBase64 = false; // base 64 存储图片
      data.editor.config.uploadImgServer = baseURL + '/admin/picture/uploadPicture?directoryName=name' // 配置服务器端地址
      data.editor.config.uploadFileName = 'file' // 后端接受上传文件的参数名

      data.editor.config.uploadImgHooks = {
        fail: (xhr, editor, result) => {
          console.log(result)
          // 插入图片失败回调
        },
        success: (xhr, editor, result) => {
          console.log(result)
        },
        timeout: (xhr, editor) => {
          // 网络超时的回调
        },
        error: (xhr, editor) => {
          console.log(111)
          // 图片上传错误的回调
        },
        customInsert: (insertImg, result, editor) => {
          // 图片上传成功，插入图片的回调
          //result为上传图片成功的时候返回的数据，这里我打印了一下发现后台返回的是data：[{url:"路径的形式"},...]
          //这块一定要细心，因为会影响到上传图片成功之后的回显
          console.log(result, 9999999)
          let url = result.object
          insertImg(url)
        }
      }
      data.editor.config.onchange = html => {
        console.log(html)
        data.form.content = html // 绑定当前逐渐地值
      }
      data.editor.create()
    }
    // 新增
    const add = () => {
      modalTitle.value = '新增'
      data.form = { top: 0 }
      // data.contentImg = [];
      data.titleImgPath = []
      data.editor = ''
      setTimeout(() => {
        initEditor()
      }, 500)
      data.visible = true
    }
    const edit = async (item, name = '编辑') => {
      // item.typeId = String(item.typeId);
      console.log(item, 'item')
      data.form = item
      data.editor = ''
      setTimeout(() => {
        initEditor()
        data.editor.txt.html(item.content)
        // data.form.content = item.content
      }, 500)
      // data.consumables = item.consumables.map((el) => el.id);
      modalTitle.value = name
      // if (item.contentImg.length > 0) {
      //   data.contentImg = item.contentImg.map((m, index) => {
      //     return {
      //       url: m,
      //       name: "1" + index + ".jpeg",
      //       status: "done",
      //     };
      //   });
      // }

      data.titleImgPath = [{ url: item.titleImgPath, status: 'done' }]
      // data.value[0] = String(item.typeId);
      data.visible = true
    }
    const Typename = id => {
      let item = data.typeList.find(el => el.id == id)
      console.log(item, '分类名字是')
      return item
    }

    const serviceName = id => {
      let list = data.serviceList.find(el => el.id == id)
      if (list.serviceName) {
        // return list.serveName;
        return list
      }
    }
    const save = () => {
      data.form.typeId = data.value[0]
      data.form.serviceId = data.value[1]
      console.log(data.form, '表单内容是')

      formRef.value.validate().then(async () => {
        let arr = []
        // 查找耗材包明细内容两个数组比较
        data.detaiList.forEach(el => {
          data.consumables.forEach(item => {
            if (item == el.id) {
              arr.push(el)
            }
          })
        })
        if (data.value.length == 0) {
          message.error('请选择耗材分类!!!')
          return
        }

        data.form.consumables = arr
        let res = await updateAndAddConsumableBag(data.form)
        if (res.success) {
          message.success('新增成功')
          data.visible = false
        }
      })
    }
    const closeModal = e => {
      data[e] = false
      if (e == 'visible') {
        data.form = { top: 0 }
        data.titleImgPath = []
        // data.contentImg = [];
      }
    }
    // 新增
    const addArticle = async () => {
      formRef.value.validate().then(async () => {
        let res = null
        if (data.titleImgPath.length == 0) {
          message.error('请上传列表图！')
          return
        }
        // if (data.contentImg.length == 0) {
        //   message.error("请上传内容图！");
        //   return;
        // }
        // titleImgPath列表图
        data.form.titleImgPath = data.titleImgPath[0].url

        // data.form.contentImg = data.contentImg.map((m) => {
        //   return m.url;
        // });
        // if (data.flag) return;
        // data.flag = true;

        data.form.top = data.form.top ? 1 : 0
        console.log(data.form)
        if (!data.form.id) {
          res = await api.add({ ...data.form })
        } else {
          res = await api.edit({ ...data.form })
          console.log(res)
        }
        if (res.success) {
          message.success('操作成功')
          data.visible = false
          init()
          // data.flag = false;
        }
      })
      init()
    }

    // 置顶
    const handleToTop = async key => {
      let res = await api.toTop({ id: Number(key) })
      if (res.success) {
        message.success('置顶成功')
        init()
      }
    }
    // 删除
    const del = key => {
      const { closeModal } = useModal.confirm({
        title: () => '你确定删除当前项吗?',
        icon: () => createVNode(QuestionCircleOutlined),
        content: () =>
          createVNode(
            'div',
            {
              style: 'color:red;'
            },
            '删除当前数据后不可恢复，请谨慎考虑。'
          ),
        onOk: async () => {
          let res = await api.deleteItem({ id: Number(key) })
          if (res.success) {
            message.success('删除成功')
            init()
            closeModal()
          }
        },

        class: 'test'
      })
    }
    const selectConsume = e => {
      console.log(e)
    }
    const selectService = e => {
      // console.log(e, "服务类型");s
    }
    const selectType = e => {}
    // 上传头图
    const uploadDetail_image = file => {
      uploadImage(file, 'titleImgPath')
    }
    // const uploadDetail_imgPath = (file) => {
    //   uploadImage(file, "contentImg");
    // };
    // 公共的上传图片
    const uploadImage = async (file, e) => {
      let formData = new FormData()
      formData.append('file', file.file)
      let res = await uploadPicture(formData, 'ali')
      // // url存入列表中,为什么是两个fileList
      data[e] = data[e].filter(el => el.status == 'done')
      if (res.success) {
        data[e].push({
          uid: file.file.uid,
          url: res.object,
          status: 'done',
          name: file.file.name
        })
      }
      console.log(data[e], 'data[e]是--')
    }
    // 全选反选
    const rowSelection = ref({
      checkStrictly: false,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
        delListId.value = selectedRowKeys
      },
      onSelect: (record, selected, selectedRows) => {
        //console.log(record, selected, selectedRows,'选择多项');
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        //console.log(selected, selectedRows, changeRows,'全选操作');
        // 数组项
      }
    })
    // 删除多项
    const listDel = () => {
      const { closeModal } = useModal.confirm({
        title: '确定删除所选内容项吗?',
        icon: createVNode(ExclamationCircleOutlined),
        content: '删除后将不可恢复，请谨慎操作。',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: async () => {
          console.log(delListId.value)
          let data = delListId.value.map(el => (el = Number(el)))

          let res = await deleteConsumableBag(data)
          if (res.success) {
            message.success('删除成功')
            init()
            closeModal()
          }
        }
      })
    }

    // 是否上下架 就把原来的状态改变下就行，传递下当前项的耗材ID即可，
    const changeStack = (checked, index, id) => {
      console.log(page.pageNum)
      console.log(checked, index, '是否上下架')
      let title = checked == 0 ? '上架' : '下架'
      // 弹框提示？确定上下架吗
      const { closeModal } = useModal.confirm({
        title: () => `确定${title}当前耗材包吗?`,
        icon: () => createVNode(ExclamationCircleOutlined),
        onOk: async () => {
          let res = await upOrDownConsumableBag(id)
          if (res.success) {
            data.list[index].status = Number(checked)
            closeModal()
          }
        },
        onCancel() {
          let flag = checked == 0 ? 1 : 0
          data.list[index].status = flag
          closeModal()
        },
        class: 'test'
      })
    }
    initServiceList()

    init()
    initAllDetailList()
    async function init() {
      let obj = {
        pageNum: page.current,
        pageSize: page.pageSize
      }
      if (data.searchForm) {
        obj.titleOrnumber = data.searchForm.titleOrnumber
        obj.type = data.searchForm.type
      }
      let res = await api.list(obj)
      if (res.success) {
        console.log(res, 'res')
        res.object.list.map(el => (el.key = el.id))
        data.list = res.object.list
        // let filteredList = res.object.list.filter((item) => item.type === 1);

        // 将辅助数组赋值给 data.list
        // data.list = filteredList;
        // data.list = res.object.list.filter((item) => item.type === 1);
        data.loading = false
        page.total = res.object.total
      }
    }
    // 一级分类
    async function initServiceList() {
      let obj = {
        pageNum: 1,
        pageSize: 80
      }
      let res1 = await selectAllType(obj)
      if (res1.success) {
        res1.object.records.map(el => (el.isLeaf = false)) //id是string类型的
        data.typeList = res1.object.records
      }
    }
    async function initAllDetailList() {
      // let res = await selectAllDetail();
      // if (res.success) {
      //   data.detaiList = res.object;
      // }
    }

    const loadData = async selectedOptions => {
      console.log('点击了选择', selectedOptions)
      const targetOption = selectedOptions[selectedOptions.length - 1]
      targetOption.loading = true // load options lazily

      let obj = {
        pageNum: 1,
        pageSize: 80,
        typeId: selectedOptions[0].id
      }
      let res = await selectAllService(obj)
      if (res.success) {
        targetOption.loading = false
        res.object.records.map(el => (el.name = el.serveName))
        targetOption.children = res.object.records

        data.typeList = [...data.typeList]
      }
    }
    return {
      ...toRefs(data),
      artStatusOptions,
      searchRef,
      modalTitle,
      formRef,
      rules,
      rules1,
      columns,
      pagination,
      title,
      labelCol: { style: { width: '150px' } },
      wrapperCol: { span: 14 },
      handleTableChange,
      search,
      add,
      del,
      addArticle,
      handleToTop,
      save,
      cancel,
      edit,
      rowSelection,
      listDel,
      changeStack,
      serviceName,
      selectConsume,
      selectService,
      chooseStatus,
      Typename,
      selectType,
      loadData,
      uploadDetail_image,
      // uploadDetail_imgPath,
      closeModal,
      reset,
      editorElem
    }
  },

  components: {
    CheckOutlined,
    EditOutlined,
    ExclamationCircleOutlined,
    QuestionCircleOutlined,
    PlusOutlined
  }
}
</script>

<style scoped lang="less">
.act {
  color: #2a9d8f;
}
</style>
